package com.CmJava.Dubbo.consumer.httpClient;

import com.CmJava.Dubbo.consumer.httpClient.parameters.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

public class HttpClient {

    public String post(String hostName , String port, String hostPath, Invocation invocation){
        String result="";
        InputStream inputStream=null;
        OutputStream outputStream=null;
        ObjectOutputStream objectOutputStream=null;

        try {
            URL url = new URL("http", hostName,Integer.parseInt(port), hostPath);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);

            outputStream = httpURLConnection.getOutputStream();
            objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(invocation);

            objectOutputStream.flush();

            inputStream = httpURLConnection.getInputStream();
            result = IOUtils.toString(inputStream);

            System.out.println("执行结果："+result);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (outputStream!=null && objectOutputStream!=null && inputStream!=null) {
                try {
                    inputStream.close();
                    outputStream.close();
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return result;
        }
    }
}
